package com.xzcs.util.mail;

import com.xzcs.util.common.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.mail.*;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeUtility;
import java.io.UnsupportedEncodingException;
import java.util.*;

public class EmailReceiveUtils {
	public final Logger log = LoggerFactory.getLogger(this.getClass());
	private Session session; // 邮件会话对象
	private Properties properties; // 系统属性
	private String username = ""; // smtp认证账户
	private String password = ""; // smtp认证账户密码
	private boolean sslFlag = false;
	
	public EmailReceiveUtils(boolean sslFlag){
		this.sslFlag = sslFlag;
	}
	
    /**
     * 设置pop主机 
     * @param popHost
     * @param popPort
     */
    public void setPopHost(String popHost, String popPort) {
        log.debug("mail.pop3.host = " + popHost);
        log.debug("mail.pop3.port = " + popPort);
        if(properties == null) {
            properties = System.getProperties(); // 获得系统属性对象
        }
        properties.put("mail.pop3.host", popHost); // 设置SMTP主机
        properties.put("mail.pop3.port", popPort); // 设置SMTP主机端口
        
        if (sslFlag) {
        	properties.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");  
            properties.setProperty("mail.pop3.socketFactory.fallback", "false");  
            properties.setProperty("mail.pop3.socketFactory.port", popPort);  
		}
    }
    
    /**
     * 收件人邮箱名称和密码
     * @param name
     * @param pass
     */
    public void setNamePass(String name, String pass) {
        this.username = name;
        this.password = pass;
    }
    
    public List<Email> receiveEmail(String popHost, String popPort, String userName, String userPwd){
    	List<Email> emails = new ArrayList<Email>();
    	try {
			setPopHost(popHost, popPort);
			setNamePass(userName, userPwd);
			session = Session.getInstance(properties);
			//URLName urln = new URLName("pop3", popHost, popPort,null, userName, userPwd);
			Store store = session.getStore("pop3");
			//如果需要查看接收邮件的详细信息，需要设置Debug标志
			session.setDebug(false);
			//连接邮件服务器
			store.connect(popHost, username, password);
			Folder inbox = store.getFolder("INBOX");
			inbox.open(Folder.READ_ONLY);
			FetchProfile profile = new FetchProfile();
			profile.add(FetchProfile.Item.ENVELOPE);
			Message[] messages = inbox.getMessages();
			inbox.fetch(messages, profile);
			System.out.println("收件箱的邮件数：" + messages.length);
			for (Message message : messages) {
				Email email = new Email();
				String from = decodeText(message.getFrom()[0].toString());
				InternetAddress ia = new InternetAddress(from);
				email.setFromPersonal(ia.getPersonal());
				email.setFromAddress(ia.getAddress());
				Address[] toAddress = message.getRecipients(RecipientType.TO);
				Address[] ccAddress = message.getRecipients(RecipientType.CC);
				Address[] bccAddress = message.getRecipients(RecipientType.BCC);
				String[] to = new String[toAddress.length];
				for (int i = 0; i < toAddress.length; i++) {
					to[i] = decodeText(toAddress[i].toString());
				}
				email.setTo(to);
				if (null != ccAddress) {
					String[] cc = new String[ccAddress.length];
					for (int i = 0; i < ccAddress.length; i++) {
						cc[i] = decodeText(ccAddress[i].toString());
					}
					email.setCc(cc);
				}
				if (null != bccAddress) {
					String[] bcc = new String[bccAddress.length];
					for (int i = 0; i < bccAddress.length; i++) {
						bcc[i] = decodeText(bccAddress[i].toString());
					}
					email.setBcc(bcc);
				}
				String subject = message.getSubject();
				email.setSubject(subject);
				email.setSendDate(DateUtils.date2String(message.getSentDate(), "yyyy-MM-dd HH:mm:ss"));
				email.setSize(message.getSize());
				email.setReceiveDate("");
				String contentType = message.getContentType();
				if (contentType.contains("multipart/")) {
					Multipart multipart = (Multipart)message.getContent();
					List<Map<String, Object>> attachments = new ArrayList<Map<String, Object>>();
					for (int i=0, n=multipart.getCount(); i<n; i++) {  
						Part part = multipart.getBodyPart(i);   
						String disposition = part.getDisposition();   
						if (null != disposition &&        
								(disposition.equals(Part.ATTACHMENT) ||         
								 disposition.equals(Part.INLINE))) {     
							Map<String, Object> map = new HashMap<String, Object>();
							map.put("fileName", decodeText(part.getFileName()));
							map.put("fileInput", part.getInputStream());
							attachments.add(map);
						} else {
							email.setContent(part.getContent().toString());
						}
					}
					email.setAttachments(attachments);
				}
				emails.add(email);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
    	return emails;
    }
    
    public String decodeText(String text) {
    	if (null == text){
    		return "";
    	}
    	try {
			if (text.startsWith("=?GB") || text.startsWith("=?gb")){
				text = MimeUtility.decodeText(text);
			} else {
				text = new String(text.getBytes("ISO8859_1"));
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
    	return text;  
	}  
    
    public static void main(String[] args) {
    	EmailReceiveUtils mailHelper = new EmailReceiveUtils(true);
    	mailHelper.receiveEmail("pop.exmail.qq.com", "995", "changs@njruiyue.cn", "cs19870115");
	}
}
